<template>
  <div>
    <h2>客服页面</h2>
    展示在线用户
    <ul>
      <li v-for="(item, i) in list" :key="i">
        <el-button @click="choseid(item.id)">{{ item.mobile }}</el-button>
      </li>
    </ul>
    <el-input placeholder="请输入" v-model="message"></el-input>
    <el-button @click="send">发送</el-button>
    展示聊天内容：
    <ul>
      <li v-for="i in meslist">{{ i }}</li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      ws: "",
      list: [],
      message: "",
      meslist: [],
      userid: "",
      name: "",
      choseuserid: "",
    };
  },
  methods: {
    initWebsocket() {
      this.userid = "kefu";
      this.name = "客服" + this.userid;
      this.ws = new WebSocket(
        "ws://localhost:8000/webuser?id=" + this.userid + "&mobile=" + this.name
      );
      this.ws.onopen = function () {
        alert("success");
      };
      this.ws.onmessage = (data) => {
        console.log(data.data);
        var mes = JSON.parse(data.data);
        this.meslist.push(mes["mes"]);
        this.list = mes["userlist"];
      };

      this.ws.onclose = function () {
        alert("close");
      };
    },
    send() {
      if (this.choseuserid) {
        var mes = this.name + "说:" + this.message;
        this.meslist.push(mes);
        var sendmes = JSON.stringify({ id: this.choseuserid, mes: mes });
        this.ws.send(sendmes);
      } else {
        alert("请先选择回复的用户");
      }
    },
    choseid(id) {
      this.choseuserid = id;
    },
  },
  mounted() {
    this.initWebsocket();
  },
};
</script>

<style>
</style>